import { _decorator, Component, resources, SpriteFrame } from 'cc';
import { createUINode, randomByRange } from '../../utils';
import { TileManager } from './TileManager';
import DataManager from '../../Runtime/DataManager';
import ResourceManager from '../../Runtime/ResourceManager';
const { ccclass } = _decorator;


@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
      const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile')
      const { mapInfo } = DataManager.Instance
      DataManager.Instance.tileInfo = []
      for (let i = 0; i < mapInfo.length; i++) {
        const colume = mapInfo[i]
        DataManager.Instance.tileInfo[i] = []
        for (let j = 0; j < colume.length; j++) {
          const item = colume[j]
          if (item.src === null || item.type === null) {
            continue
          }

          let imgNumber = item.src
          if ((imgNumber === 1 || imgNumber === 5 || imgNumber === 9) && i % 2 === 0 && j % 2 === 0) {
            imgNumber += randomByRange(0, 4)
          }
          const imgSrc = `tile (${imgNumber})`
          const node = createUINode()
          const spriteFrame = spriteFrames.find(v => v.name === imgSrc) || spriteFrames[0]

          const tileManager = node.addComponent(TileManager)
          const type = item.type
          tileManager.init(type, spriteFrame, i, j)
          DataManager.Instance.tileInfo[i][j] = tileManager
          node.setParent(this.node)
        }
      }
  }
}
